package com.fingard.dsp.bank.directbank.hnrcb01;

import com.alibaba.fastjson.JSONObject;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionParams;

import javax.net.ssl.SSLContext;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.Socket;
import java.util.Date;

public class HNRCB01Base extends DirectBase implements ITcpClient {
    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        return Format.Date10Format4.format(new Date()).substring(2) + idHelper.getNextIDStr();
    }

    public void writeSignXml(XmlTextWriter writerXml, String data) throws Exception {
        String charset = getBankConfig().getValueAsString("signCharset");
        writerXml.writeStartDocByDeclaration("<?xml version=1.0 encoding='" + charset + "'?>");
        writerXml.writeStartElement("msg");
        writerXml.writeStartElement("msg_head");
        writerXml.writeElementString("msg_type", "0");//固定参数
        writerXml.writeElementString("msg_id", "1005");//固定参数
        writerXml.writeElementString("msg_sn", "0");//固定参数
        writerXml.writeElementString("version", "1");//固定参数
        writerXml.writeEndElement();//msg_head
        writerXml.writeStartElement("msg_body");
        writerXml.writeElementString("origin_data_len", data.trim().getBytes(charset).length + "");
        writerXml.writeElementString("origin_data", data.trim());
        writerXml.writeEndDocument();

    }

    public void writeCommonHeader(HNRCB01Header hnrcb01Header, JSONObject reqJson) {
        JSONObject headerJson = new JSONObject();
        headerJson.put("TRSCODE", hnrcb01Header.trsCode);//交易码
        headerJson.put("BRANCHID", bankFront.org);//签约机构号
        headerJson.put("USERID", bankFront.loginName);//用户号
        headerJson.put("USERNAME", bankFront.corpNo);//客户姓名
        headerJson.put("ENTOPERID", bankFront.operator);//企网操作员ID
        headerJson.put("ENTOPERNAME", bankFront.userName);//企网操作员姓名
        headerJson.put("SIGNATUREDATA", hnrcb01Header.signaturedata);//加签密文
        headerJson.put("REQSEQNO", hnrcb01Header.reqSeqno);//流水号

        reqJson.put("head", headerJson);
    }

    /**
     * 发送并获取返回
     *
     * @return 响应JOSN
     * @throws Exception 服务器请求异常
     */
    public String[] sendToBank(String tmpReqMsg, String transType, String commandCode) throws Exception {
        String[] retStr = new String[]{"", ""};
        if (StringHelper.hasAnyChar(transType) && StringHelper.hasAnyChar(commandCode)) {
            this.detailSimulateForBank(bankFront.bankCode, transType, commandCode, tmpReqMsg, retStr);
            if (retStr[1].length() > 0) {
                return retStr;
            }
        }
        WriteBankLogLn("发送银行的地址：" + bankFront.serverURL);

        // 发送银行前置
        WebRequest tmpRequest = new WebRequest(bankFront.serverURL);
        tmpRequest.setConnectTimeout(10000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type", "application/json");
        String charsetName = getCharset();
        StringBuilder data = new StringBuilder();
        data.append(tmpReqMsg);
        WriteBankLogLn("发送银行的数据" + data.toString());
        byte[] tmpWriteBytes = data.toString().getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("银行返回的数据" + retStr[1]);

        return retStr;
    }

    //签名服务
    public String[] sendToBankBySign(String data) throws Exception {
        String charset = getBankConfig().getValueAsString("signCharset");
        String ip = bankFront.serverIP;
        int port = Integer.parseInt(bankFront.signPort);
        WriteBankLogLn("发送签名服务地址：" + ip + ":" + port);
        byte[] tmpBytes = data.getBytes(charset);
        int XMLlength = tmpBytes.length;
        StringBuilder reqContext = new StringBuilder(data).insert(0, String.format("%05d", XMLlength));
        WriteBankLogLn("发送银行的签名报文：" + reqContext.toString());
        //发送银行前置
        String[] retStr = new String[]{"", ""};
        TcpPortClient tmpClient = new TcpPortClient(ip, port, this);
        tmpClient.timeoutMil = 300000;
        TcpReceiver tmpReceiver = tmpClient.sendMessage(reqContext.toString(), charset);
        retStr[0] = tmpReceiver.connState;
        retStr[1] = tmpReceiver.getFullString(charset);
        if (StringHelper.isNullOrEmpty(retStr[1])) {
            retStr[1] = tmpReceiver.getConnMsg();
        } else {
            retStr[1] = tmpReceiver.getFullString(charset);
            int idx = retStr[1].indexOf("<msg>");
            if (idx != -1) {
                retStr[1] = retStr[1].substring(idx);
            }
        }
        WriteBankLogStep3(retStr[1]);
        return retStr;

//        String[] retStr = new String[]{"", ""};
//        //发送银行前置
//        StringBuffer sb = new StringBuffer("");
//        Socket socket = null;
//        BufferedInputStream in = null;
//        BufferedOutputStream out = null;
//        try {
//            int length = data.getBytes(charset).length;
//            byte[] buf = new byte[length + 5];
//            String lenValue = String.valueOf(length);
//            System.arraycopy(data.getBytes(charset), 0, buf, 5, length);
//            for (int i = 0; i < 5; i++)
//                buf[i] = '0';
//            int idx = 0;
//            for (int i = 5 - lenValue.length(); i < 5; i++) {
//                buf[i] = (byte) lenValue.charAt(idx++);
//            }
//            socket = new Socket(ip, port);
//            out = new BufferedOutputStream(socket.getOutputStream());
//            WriteBankLogLn("发送银行的签名报文：" + new String(buf, charset));
//            out.write(buf);
//            out.flush();
//            in = new BufferedInputStream(socket.getInputStream());
//            byte[] buffer = new byte[1024];
//            int len = 0;
//            while ((len = in.read(buffer)) != -1) {
//                sb.append(new String(buffer, 0, len, charset));
//            }
//        } catch (Exception e) {
//            sb = new StringBuffer("-1");
//            e.printStackTrace();
//        } finally {
//            try {
//                if (null != socket) {
//                    socket.close();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            try {
//                if (out != null)
//                    out.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            try {
//                if (in != null)
//                    in.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        WriteBankLogLn("通讯签名返回数据：\r\n" + sb.toString());
//        retStr[1] = sb.toString();
//        return retStr;
    }


    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            String tmpCharset = getCharset();
            String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
            if (tmpRecNow.contains("</msg>")) {
                p_receiver.contentLength = p_receiver.readedLength;
                p_receiver.contentStartIndex = 0;
            }
        }
    }
}
